/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief MaCI Text Main Frame implementation 
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 * \author wxFormBuilder (Autogenerated base code)
 *
 * $Id: MaCI_Text_MaCITextFrame.cpp,v 1.4 2009-07-21 09:08:33 morsko Exp $
 *
 */
#include "MaCI_Text_MaCITextFrame.h"

DEFINE_EVENT_TYPE(MY_EVENT_MESSAGEFROMSERVER);
DEFINE_EVENT_TYPE(MY_EVENT_TEXTFROMSERVER);
//cretae event table for catching custom event
BEGIN_EVENT_TABLE(MaCI_Text_MaCITextFrame, wxFrame)
  EVT_COMMAND(wxID_ANY, MY_EVENT_MESSAGEFROMSERVER, MaCI_Text_MaCITextFrame::OnMessageFromServer)
  EVT_COMMAND(wxID_ANY, MY_EVENT_TEXTFROMSERVER, MaCI_Text_MaCITextFrame::OnTextEventFromServer)
END_EVENT_TABLE();
MaCI_Text_MaCITextFrame::MaCI_Text_MaCITextFrame( wxWindow* parent )
:
  MaCITextFrame( parent ),
  iGIMIPtr(NULL),
  iServiceList(),
  iTextClientArray()
{

}
//*****************************************************************************

MaCI_Text_MaCITextFrame::~MaCI_Text_MaCITextFrame()
{
  Deinitialize();

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnSendClick( wxCommandEvent& event )
{
  //Do not send if empty text field is empty
  if(m_textCtrl_Text->GetNumberOfLines() == 1 && m_textCtrl_Text->GetLineLength(0) == 0){
    wxString status = "No text to send\n";
    m_textCtrl_Status->WriteText(status);
    return;
  }


  wxString wxs;
  for(int i = 0; i<m_textCtrl_Text->GetNumberOfLines();i++){
    
    wxs += m_textCtrl_Text->GetLineText(i);
    if(i+1 != m_textCtrl_Text->GetNumberOfLines()){
      wxs += "\n";
    }
    
  }


  std::string s = std::string(wxs.mb_str(wxConvUTF8));
  bool clientSelected = false;
  for(int i = 0; i< iTextClientArray.size();i++){
    if( m_listBox_Services->IsSelected(i)){
      clientSelected = true;
      if(iTextClientArray[i]->SendText(s)){
        wxString status = "Sent text '" + wxs +"' to '" +m_listBox_Services->GetString(i) + "'\n";
        m_textCtrl_Status->SetDefaultStyle(wxTextAttr(*wxGREEN));
        m_textCtrl_Status->WriteText(status);
      }else{
        wxString status ="Failed to send text to '" + m_listBox_Services->GetString(i) + "'\n";
        m_textCtrl_Status->SetDefaultStyle(wxTextAttr(*wxRED));
        m_textCtrl_Status->WriteText(status);
      }
    }

  }
  if(!clientSelected){
    wxString status = "Unable to send text. Please select service\n";
    m_textCtrl_Status->WriteText(status);
  }
}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnClearTextClick( wxCommandEvent& event )
{
  m_textCtrl_Text->Clear();
}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnServiceAssignment(const Gimbo::TServiceAssignmentList &aServiceList)
{
 dPrint(10,"Event: OnServiceAssignment");
  
 // Got service list - REPLACING current.
  iServiceList = aServiceList;
   
  // Disconnect services (if any)
  DisconnectServices();

  dPrint(10,"Disconnect - Done");

  // Connect services.
  ConnectServices();

  // RequestUpdateStatusBar();

  dPrint(10,"Connect - Done");

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::DisconnectServices(void)
{
  dPrint(ODTEST,"DisconnectServices() (%u entries in array)", iTextClientArray.size());
  // Call Close() on all Clients and then delete.
  for(EACH_IN_i(iTextClientArray)) {
    (*i)->Close();
    delete *i;
  }
  
  // Clear the array.
  iTextClientArray.clear();
}
//*****************************************************************************

bool MaCI_Text_MaCITextFrame::ConnectServices(void)
{
  
  bool result = iServiceList.size() > 0;
  dPrint(ODTEST,"ConnectServices()");
  unsigned int clientNumber = 0;
  assert(iGIMIPtr != NULL);
  for(EACH_IN_i(iServiceList)) {
    // Create new instance
    MaCI::Text::CTextClient *tc = new MaCI::Text::CTextClient(iGIMIPtr, i->minorType);
    assert(tc != NULL);

    dPrint(10,"Constructed new BehaviourClient (Minor: %d)", i->minorType);
    
    // Assign
    dPrint(10,"Setting Default target : 0x%08x", i->targetID);
    tc->SetDefaultTarget(i->targetID);
    
    // Open!
    dPrint(10,"Calling Open()");
    MaCI::EMaCIError e = tc->Open();

    //Then get MaCI name
    if (e == MaCI::KMaCIOK) {
      dPrint(ODTEST,"Successfully opened TextClient to target: '%u', using minor %u.", 
             i->targetID, i->minorType);
      
      
      const MaCI::MaCICtrl::SMaCISL sl = tc->GetDefaultTargetMaCISL();
      wxString textServerName;

      MaCI::MaCICtrl::CMaCICtrlClient MaCICtrl(GetGimi());
      
      if (MaCICtrl.Open()!=MaCI::KMaCIOK){
        
        dPrint(5,"Couldn't open MaCICtrl client");
      }
      
      //Get names
      MaCI::MaCICtrl::TServiceEntryArray services;
      MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
      int counter = 0;
      bool found = false;
      while (!found && counter<=5){
        MaCICtrl.GetServiceArray(services, tc->GetDefaultTarget(),counter,1000);
        counter++;
        //for (iter=services.begin();iter!=services.end();iter++)
          if (services.size())
            {
              for (iter=services.begin();iter!=services.end();iter++)
                {
                  if (iter->service.servicemajor==i->majorType && 
                      iter->service.serviceminor==i->minorType)
                    {
                      found=true;
                      break;
                    }
                }
            }
         
      }

      if(found){
        textServerName = iter->GetMaCISL().ToMaCISLString().c_str();
        dPrint(10,"Name is %s", iter->GetMaCISL().ToMaCISLString().c_str());
      } else {
        dPrint(10,"Not valid");
        textServerName = tc->GetDefaultTarget();
        
      } 
      
      
      //Insert item name
      m_listBox_Services->InsertItems((unsigned int)1,&textServerName, clientNumber);
      
      
      clientNumber++;

      //Register handler
      tc->SetTextClientCallback(this);

      //Add client to array
      iTextClientArray.push_back(tc);
      
     


    } else {
      dPrint(10,"Failed to Connect to TextServer at target: '%u', using minor %u!",
             i->targetID, i->minorType);
      delete tc;
    }
  }
  //Automatically select the first client if available
  if(m_listBox_Services->GetCount() != 0){
    m_listBox_Services->Select(0);
  }
  return result;
}
//*****************************************************************************

bool MaCI_Text_MaCITextFrame::Initialize(gimi::GIMI *aGimiPtr, int aGimboID, int aReportID)
{
  bool result = true;
  dPrint(10,"Initializing");
  // Store for future reference.
  iGIMIPtr = aGimiPtr;
  
  // Start the Gimbo core.
  CComponent::Start(aGimiPtr, aGimboID, aReportID);
  
  // Unconditional LoadConfig.
  //  LoadConfig();

   
  return result;

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::Deinitialize(void)
{
 
  DisconnectServices();

}
//*****************************************************************************
void MaCI_Text_MaCITextFrame::OnTextFromServer(std::string &aText, 
                                               const unsigned int aDataSequence,
                                               MaCI::Text::CTextClient &aTextClient)
{
   for(int i = 0; i< iTextClientArray.size();i++){
     if(iTextClientArray[i] == &aTextClient){
       wxString s= "Got '" + aText + "' from '" + m_listBox_Services->GetString(i) + "'\n";
       wxCommandEvent e( MY_EVENT_TEXTFROMSERVER, GetId() );
       e.SetString(s);
       AddPendingEvent(e);
     }
   }

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnTextReplyFromServer(std::string &aText, 
                                                    const unsigned int aDataSequence,
                                                    MaCI::Text::CTextClient &aTextClient)
{
   for(int i = 0; i< iTextClientArray.size();i++){
     if(iTextClientArray[i] == &aTextClient){
       wxString s= "'" + aText + "' accomplished at '" + m_listBox_Services->GetString(i) + "'\n";
       wxCommandEvent e( MY_EVENT_MESSAGEFROMSERVER, GetId() );
       e.SetString(s);
       AddPendingEvent(e);
     }
   }

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnMessageFromServer(wxCommandEvent &aEvent)
{
 
  m_textCtrl_Status->SetDefaultStyle(wxTextAttr(*wxBLACK));
  m_textCtrl_Status->AppendText(aEvent.GetString());

}
//*****************************************************************************

void MaCI_Text_MaCITextFrame::OnTextEventFromServer(wxCommandEvent &aEvent)
{
  m_textCtrl_Status->SetDefaultStyle(wxTextAttr(*wxBLUE));
  m_textCtrl_Status->AppendText(aEvent.GetString());
}
//*****************************************************************************
